package com.diver.flinkdemo.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diver.flinkdemo.dto.xxt.C40DataVO;
import com.diver.flinkdemo.entity.xxt.ClockSettings;
import com.diver.flinkdemo.mapper.mysqlMapper.ClockSettingsMapper;
import com.diver.flinkdemo.service.IClockSettingsService;
import com.diver.flinkdemo.utils.DynamicDataSourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hesc
 * @since 2022-03-04
 */
@Slf4j
public class ClockSettingsServiceImpl implements IClockSettingsService {
//    @Autowired
//    private KafkaClient kafkaClient;
//    @Autowired(required = false)
    private ClockSettingsMapper mapper;
    private SqlSession session = null;

    @Override
    public List<ClockSettings> getClockSettingsList(String imei) {
        try {
            session = DynamicDataSourceUtil.mysqlSessionFactory.openSession();
            mapper = session.getMapper(ClockSettingsMapper.class);
            return mapper.selectList(new QueryWrapper<ClockSettings>().eq("imei", imei).eq("del_flag", "0").orderByDesc("create_time"));
        } finally {
            endOfSession(session);
        }
    }

    @Override
    public synchronized String addClockSettings(String uid, String imei, Integer clockType, Integer clockStatus, String settingTime, String clockInstruct, String userId) {
//        Long time = System.currentTimeMillis();
//        if(StringUtils.isEmpty(uid)) {
//            List<ClockSettings> list = mapper.selectList(new QueryWrapper<ClockSettings>().eq("imei", imei).eq("del_flag", "0"));
//            if(list.size() >= 5) {
//                return ApiResultGenerator.errorResult(ApiResult.PARAM_ERROR_CODE, "添加失败，闹钟限可设置5个！");
//            }
//            List<ClockSettings> lists = mapper.selectList(new QueryWrapper<ClockSettings>().eq("imei", imei).eq("del_flag", "2"));
//            if(lists.size() > 0) {
//                if((list.size() + lists.size()) >= 5) {
//                    return ApiResultGenerator.errorResult(ApiResult.PARAM_ERROR_CODE, "添加失败，您有删除的闹钟正在执行指令，请稍后再添加！");
//                }
//            }
//            ClockSettings clockSettings = new ClockSettings();
//            String tagId = UUID.randomUUID().toString();
//            if(1 == clockStatus) {
//                JSONObject jo = new JSONObject();
//                jo.put("imei", imei);
//                jo.put("type", "REMIND");
//                jo.put("taskId", tagId);
//                String remindContent = "";
//                if(list.size() > 0) {
//                    Integer num = 0;
//                    for(int i=0;i<list.size();i++) {
//                        if(list.get(i).getClockStatus() == 1 || list.get(i).getClockStatus() == 3) {
//                            remindContent += list.get(i).getClockInstruct() + ",";
//                            num++;
//                        }
//                    }
//                    remindContent += clockInstruct;
//                    for(int i=0;i<(5 - num);i++) {
//                        remindContent += ",";
//                    }
//                } else {
//                    remindContent = clockInstruct + ",,,,,";
//                }
//                jo.put("remindContent", remindContent);
//                log.info("闹钟添加：imei{}，指令:{}", imei, jo);
//                //闹钟设置下发 待开启
//                kafkaClient.c40ApplicationSend(jo.toJSONString());
//                clockSettings.setClockStatus(3);
//            } else {
//                clockSettings.setClockStatus(0);
//            }
//            clockSettings.setId(UUIDUtil.uuid());
//            clockSettings.setImei(imei);
//            clockSettings.setSettingTime(settingTime);
//            clockSettings.setClockType(clockType);
//            clockSettings.setClockInstruct(clockInstruct);
//            clockSettings.setTagId(tagId);
//            clockSettings.setOperateUser(userId);
//            clockSettings.setCreateTime(time);
//            clockSettings.setDelFlag("0");
//            return ApiResultGenerator.successResult(mapper.insert(clockSettings));
//        } else {
//            ClockSettings clockSettings = mapper.selectOne(new QueryWrapper<ClockSettings>().eq("id", uid).eq("del_flag", "0"));
//            if(clockSettings == null) {
//                return ApiResultGenerator.errorResult(ApiResult.EMPTY_DATA_CODE, "该条闹钟数据不存在！");
//            }
//            if(clockStatus == 1) {
//                List<ClockSettings> list = mapper.selectList(new QueryWrapper<ClockSettings>().eq("imei", imei).eq("del_flag", "0"));
//                JSONObject jo = new JSONObject();
//                jo.put("imei", imei);
//                jo.put("type", "REMIND");
//                jo.put("taskId", clockSettings.getTagId());
//                String remindContent = "";
//                Integer num = 0;
//                for(int i=0;i<list.size();i++) {
//                    if(list.get(i).getClockStatus() == 1 || list.get(i).getClockStatus() == 3) {
//                        num++;
//                        if (uid.equals(list.get(i).getId())) {
//                            remindContent += clockInstruct + ",";
//                        } else {
//                            remindContent += list.get(i).getClockInstruct() + ",";
//                        }
//                    }
//                }
//                for(int i=0;i<(5 - num);i++) {
//                    remindContent += ",";
//                }
//                jo.put("remindContent", remindContent);
//                log.info("闹钟添加：imei{}，指令:{}", imei, jo);
//                //闹钟设置下发 待开启
//                kafkaClient.c40ApplicationSend(jo.toJSONString());
//                clockSettings.setOldClockStatus(clockSettings.getClockStatus());
//                clockSettings.setClockStatus(3);
//                clockSettings.setOldClockType(clockSettings.getClockType());
//                clockSettings.setOldSettingTime(clockSettings.getSettingTime());
//                clockSettings.setOldClockInstruct(clockSettings.getClockInstruct());
//            }
//            clockSettings.setClockInstruct(clockInstruct);
//            clockSettings.setClockType(clockType);
//            clockSettings.setSettingTime(settingTime);
//            clockSettings.setUpdateTime(time);
//            clockSettings.setOperateUser(userId);
//            return ApiResultGenerator.successResult(mapper.updateById(clockSettings));
//        }
        return "";
    }

    @Override
    public String delClockSetting(String uid, String userId) {
//        ClockSettings clockSettings = mapper.selectById(uid);
//        if(clockSettings == null) {
//            return ApiResultGenerator.errorResult(ApiResult.EMPTY_DATA_CODE, "删除失败，该条闹钟信息不存在！", null);
//        }
//        String imei = clockSettings.getImei();
//        Integer clockStatus = clockSettings.getClockStatus();
//        if(clockStatus == 0) {
//            clockSettings.setDelFlag("1");
//        } else if(clockStatus == 1) {
//            List<ClockSettings> list = mapper.selectList(new QueryWrapper<ClockSettings>().eq("imei", imei).eq("del_flag", "0"));
//            JSONObject jo = new JSONObject();
//            jo.put("imei", imei);
//            jo.put("type", "REMIND");
//            jo.put("taskId", clockSettings.getTagId());
//            String remindContent = "";
//            Integer num = 0;
//            for(int i=0;i<list.size();i++) {
//                if(list.get(i).getClockStatus() == 1 || list.get(i).getClockStatus() == 3) {
//                    if (!uid.equals(list.get(i).getId())) {
//                        remindContent += list.get(i).getClockInstruct() + ",";
//                        num++;
//                    }
//                }
//            }
//            for(int i=0;i<(5 - num);i++) {
//                remindContent += ",";
//            }
//            jo.put("remindContent", remindContent);
//            log.info("闹钟添加：imei{}，指令:{}", imei, jo);
//            //闹钟设置下发 待开启
//            kafkaClient.c40ApplicationSend(jo.toJSONString());
//            clockSettings.setDelFlag("2");
//        } else {
//            return ApiResultGenerator.errorResult(ApiResult.PARAM_ERROR_CODE, "该闹钟正在指令执行中，请稍后再试！");
//        }
//        clockSettings.setUpdateTime(System.currentTimeMillis());
//        clockSettings.setOperateUser(userId);
//        return ApiResultGenerator.successResult(mapper.updateById(clockSettings));
        return "";
    }

    @Override
    public ClockSettings updateClockStatus(String uid, String userId) {
        try {
            session = DynamicDataSourceUtil.mysqlSessionFactory.openSession();
            mapper = session.getMapper(ClockSettingsMapper.class);
            ClockSettings clockSettings = mapper.selectById(uid);
            String imei = clockSettings.getImei();
            if(clockSettings == null) {
                return null;
            }
            Integer clockStatus = clockSettings.getClockStatus();
            if(clockStatus == 0) {
                List<ClockSettings> list = mapper.selectList(new QueryWrapper<ClockSettings>().eq("imei", imei).eq("del_flag", "0"));
                JSONObject jo = new JSONObject();
                jo.put("imei", imei);
                jo.put("type", "REMIND");
                jo.put("taskId", clockSettings.getTagId());
                String remindContent = "";
                Integer num = 0;
                for(int i=0;i<list.size();i++) {
                    if(list.get(i).getClockStatus() == 1 || list.get(i).getClockStatus() == 3) {
                        if (!uid.equals(list.get(i).getId())) {
                            remindContent += list.get(i).getClockInstruct() + ",";
                            num++;
                        }
                    }
                }
                remindContent += clockSettings.getClockInstruct();
                for(int i=0;i<(5 - num);i++) {
                    remindContent += ",";
                }
                jo.put("remindContent", remindContent);
                log.info("闹钟添加：imei{}，指令:{}", imei, jo);
                //闹钟设置下发 待开启
    //            kafkaClient.c40ApplicationSend(jo.toJSONString());
                clockSettings.setOldClockStatus(clockSettings.getClockStatus());
                clockSettings.setClockStatus(3);
                clockSettings.setOldClockType(clockSettings.getClockType());
                clockSettings.setOldSettingTime(clockSettings.getSettingTime());
                clockSettings.setOldClockInstruct(clockSettings.getClockInstruct());
            } else if(clockStatus == 1) {
                List<ClockSettings> list = mapper.selectList(new QueryWrapper<ClockSettings>().eq("imei", imei).eq("del_flag", "0"));
                JSONObject jo = new JSONObject();
                jo.put("imei", imei);
                jo.put("type", "REMIND");
                jo.put("taskId", clockSettings.getTagId());
                String remindContent = "";
                Integer num = 0;
                for(int i=0;i<list.size();i++) {
                    if(list.get(i).getClockStatus() == 1 || list.get(i).getClockStatus() == 3) {
                        if (!uid.equals(list.get(i).getId())) {
                            remindContent += list.get(i).getClockInstruct() + ",";
                            num++;
                        }
                    }
                }
                for(int i=0;i<(5 - num);i++) {
                    remindContent += ",";
                }
                jo.put("remindContent", remindContent);
                log.info("闹钟添加：imei{}，指令:{}", imei, jo);
                //闹钟设置下发 待开启
    //            kafkaClient.c40ApplicationSend(jo.toJSONString());
                clockSettings.setClockStatus(2);
            } else {
                return null;
            }
            clockSettings.setUpdateTime(System.currentTimeMillis());
            mapper.updateById(clockSettings);
            return clockSettings;
        } finally {
            endOfSession(session);
        }
    }

    @Override
    public void updateClockSettings(C40DataVO c40DataVO) {

        try {
            session = DynamicDataSourceUtil.mysqlSessionFactory.openSession();
            mapper = session.getMapper(ClockSettingsMapper.class);
            String imei = c40DataVO.getImei();
            String status = c40DataVO.getStatus();
            String taskId = c40DataVO.getTaskId();
            log.info("闹钟设置回调，数据:{}", c40DataVO);
            if(StringUtils.isEmpty(imei)) {
                return;
            }
            List<ClockSettings> list = new ArrayList<>();
            if(StringUtils.isBlank(taskId)) {
                list = mapper.selectList(new QueryWrapper<ClockSettings>().eq("imei", imei));
            } else {
                list = mapper.selectList(new QueryWrapper<ClockSettings>().eq("imei", imei).eq("tag_id", taskId));
            }
            for(int i=0;i<list.size();i++){
                ClockSettings clockSettings = list.get(i);
                if("1".equals(status)) {
                    if("2".equals(clockSettings.getDelFlag())) {
                        clockSettings.setDelFlag("1");
                    } else if(clockSettings.getClockStatus() == 2) {
                        clockSettings.setClockStatus(0);
                    } else if(clockSettings.getClockStatus() == 3) {
                        clockSettings.setClockStatus(1);
                    } else {
                        continue;
                    }
                    clockSettings.setUpdateTime(System.currentTimeMillis());
                    int num = mapper.updateById(clockSettings);
                    log.info("修改闹钟状态：{},修改数量：{}", clockSettings, num);
                } else {
                    if("2".equals(clockSettings.getDelFlag())) {
                        clockSettings.setDelFlag("0");
                    } else if(clockSettings.getClockStatus() == 2) {
                        clockSettings.setClockStatus(1);
                    } else if(clockSettings.getClockStatus() == 3) {
                        if(clockSettings.getOldClockStatus() != null) {
                            clockSettings.setClockStatus(clockSettings.getOldClockStatus());
                            clockSettings.setClockType(clockSettings.getOldClockType());
                            clockSettings.setClockInstruct(clockSettings.getOldClockInstruct());
                            clockSettings.setSettingTime(clockSettings.getOldSettingTime());
                        } else {
                            clockSettings.setClockStatus(0);
                        }
                    } else {
                        continue;
                    }
                    clockSettings.setUpdateTime(System.currentTimeMillis());
                    int num = mapper.updateById(clockSettings);
                    log.info("修改闹钟状态：{},修改数量：{}", clockSettings, num);
                }
            }
        } finally {
            endOfSession(session);
        }
    }

    @Override
    public void updateClockStatus(String imei) {
        mapper.updateClockStatus(imei);
    }

    public void endOfSession(SqlSession session) {
        //关闭sqlSession
        if (session != null) {
            log.info("session commit -> session close");
//            session.commit();
            session.close();
        }
    }
}
